﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Kernel;

[assembly: ExtensionApplication(typeof(SppdProjectHelper.App))]
[assembly: CommandClass(typeof(SppdProjectHelper.App))]
namespace SppdProjectHelper
{
    class App : IExtensionApplication
    {
        [CommandMethod("Hello")]
        public static void Hello()
        {
            //获取当前活动文档的Editor对象
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Autodesk.AutoCAD.EditorInput.Editor edtr = doc.Editor;
            edtr.WriteMessage(string.Format("Hello , this time is {0}", DateTime.Now.ToString()));
        }

        [CommandMethod("SetLogo")]
        public static void SetLogo()
        {
            Misc.SetIcon(Resource_main.logo);
        }

        [CommandMethod("Test")]
        public static void Test()
        {
            var menu = new Autodesk.AutoCAD.Windows.ContextMenuExtension();
            menu.Title = "工程管理";
            Application.AddDefaultContextMenuExtension(menu);
        }

        [CommandMethod("Test1")]
        public static void Test1()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            ObjectId id = new ObjectId();
            using (Transaction tr = db.TransactionManager.StartTransaction())//using 自动调用Dispose()方法
            {
                //BlockTable table = tr.GetObject(db.Block)
                ObjectId ModelSpaceID = SymbolUtilityServices.GetBlockModelSpaceId(HostApplicationServices.WorkingDatabase);
                BlockTable bt = (BlockTable)tr.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                ObjectIdCollection col = btr.GetBlockReferenceIds(false, true);
                foreach(ObjectId objid in col)
                {
                    string str = objid.ToString();
                }
                //处理过程
                tr.Commit(); //事务提交
}
        }

        [CommandMethod("SetAutoLoad")]
        public static void SetAutoLoad()
        {
            Misc.AutoLoad("SppdProjectHelper", "SPPD的CAD工程管理软件", @"E:\My Vs Prj\SppdProjectHelper\SppdProjectHelper\bin\Debug\SppdProjectHelper.dll");
        }

        [CommandMethod("AddBlockDef")]
        public static void AddBlockDef()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            BlockTableRecord btr = new BlockTableRecord();
            btr.Name = "bimcad";
            Line line = new Line(Point3d.Origin, new Point3d(10, 15, 0));
            Circle circle = new Circle(Point3d.Origin, Vector3d.ZAxis, 10);
            btr.AppendEntity(line);
            btr.AppendEntity(circle);
            Common.AppendBtrToBlockTable(btr, db);
        }

        [CommandMethod("AddAttributeBlock")]
        public static void AddAttributeBlock()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            ObjectId id;
            BlockTableRecord btr = new BlockTableRecord();
            btr.Name = "LineBlock";
            Line line = new Line(Point3d.Origin, new Point3d(10, 15, 0));
            Circle circle = new Circle(Point3d.Origin, Vector3d.ZAxis, 10);
            AttributeDefinition ad = Common.AttributeDefinition("Length", "L", line.Length.ToString(), new Point3d(30, 30, 0));
            btr.AppendEntity(line);
            btr.AppendEntity(circle);
            btr.AppendEntity(ad);

            id = Common.AppendBtrToBlockTable(btr);
            Common.AppendBlkAttToModelSpace(id, Point3d.Origin, db);
            //Common.AddBlockTableRecord(btr, db);
        }

        [CommandMethod("ListAllBT")]
        public static void ListAllBT()
        {
            //获取当前活动文档的Editor对象
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Autodesk.AutoCAD.EditorInput.Editor edtr = doc.Editor;

            //ObjectId blk_rf_id = new ObjectId();
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite);
                BlockTableRecord btr_ms = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                int i = 0;
                foreach (ObjectId btr_id in bt)
                {
                    BlockTableRecord btr = tr.GetObject(btr_id, OpenMode.ForRead) as BlockTableRecord;
                    if (null != btr)
                    {
                        int j = 0;
                        Misc.WriteToTxtFile(string.Format("{0}. BlockName : {1}\r\n",i, btr_id.GetObject(OpenMode.ForRead).GetType()));
                        foreach (ObjectId ent_id in btr)
                        {
                            Misc.WriteToTxtFile(string.Format("-{0}. BlockName : {1}\r\n",j, ent_id.GetObject(OpenMode.ForRead).GetType()));
                            //if (ent_id.GetObject(OpenMode.ForRead).GetType().Equals(typeof(AttributeDefinition)))
                            //{
                            //    AttributeDefinition ad = tr.GetObject(ent_id, OpenMode.ForRead) as AttributeDefinition;

                            //    edtr.WriteMessage(string.Format("BlockName : {0} AttName : {1}\r\n", ad.BlockName, ad.Tag));
                            //}
                            j++;
                        }
                    }
                    i++;
                }

                tr.Commit();
            }
        }

        [CommandMethod("ListAllBTR")]
        public static void ListAllBTR()
        {
            //获取当前活动文档的Editor对象
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Autodesk.AutoCAD.EditorInput.Editor edtr = doc.Editor;

            //ObjectId blk_rf_id = new ObjectId();
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite);
                BlockTableRecord btr_ms = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                foreach ( ObjectId btr_id in btr_ms)
                {
                    //if (btr_id.GetObject(OpenMode.ForRead).GetType().Equals(typeof(AttributeDefinition)))
                    //{
                    //    AttributeDefinition ad = tr.GetObject(btr_id, OpenMode.ForRead) as AttributeDefinition;

                    //    edtr.WriteMessage(string.Format("BlockName : {0} AttName : {1}\r\n", ad.BlockName, ad.Tag));
                    //}
                    //edtr.WriteMessage(string.Format("BlockName : {0}\r\n", btr_id.GetObject(OpenMode.ForRead).GetType()));
                    Misc.WriteToTxtFile(string.Format("BlockName : {0}\r\n", btr_id.GetObject(OpenMode.ForRead).GetType()));
                }
                //BlockTableRecord btr_ms = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                //BlockTableRecord block = tr.GetObject(blkid, OpenMode.ForRead) as BlockTableRecord;
                //BlockReference br = new BlockReference(pt, blkid);//通过块定义，添加块参照
                //blk_rf_id = btr_ms.AppendEntity(br);//将块参照添加到块表记录
                //tr.AddNewlyCreatedDBObject(br, true);//通过事务添加块参照到数据库

                //foreach (ObjectId id in block)
                //{
                //    if (id.GetObject(OpenMode.ForRead).GetType().Equals(typeof(AttributeDefinition)))
                //    {
                //        AttributeDefinition ad = tr.GetObject(id, OpenMode.ForRead) as AttributeDefinition;
                //        AttributeReference ar = new AttributeReference(ad.Position, ad.TextString, ad.Tag, new ObjectId());
                //        br.AttributeCollection.AppendAttribute(ar);
                //    }
                //}

                tr.Commit();
            }
        }

        [CommandMethod("ListAllBR")]
        public static void ListAllBR()
        {
            //获取当前活动文档的Editor对象
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Autodesk.AutoCAD.EditorInput.Editor edtr = doc.Editor;

            //ObjectId blk_rf_id = new ObjectId();
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForWrite);
                BlockTableRecord btr_ms = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                int i = 0;
                foreach (ObjectId btr_id in bt)
                {
                    BlockTableRecord btr = tr.GetObject(btr_id, OpenMode.ForRead) as BlockTableRecord;
                    if (null != btr)
                    {
                        int j = 0;
                        Misc.WriteToTxtFile(string.Format("{0}. BlockTableRecord : {1}\r\n", i, btr_id.GetObject(OpenMode.ForRead).GetType()));
                        foreach (ObjectId ent_id in btr)
                        {
                            Misc.WriteToTxtFile(string.Format("-{0}. EntityName : {1}\r\n", j, ent_id.GetObject(OpenMode.ForRead).GetType()));
                            if (ent_id.GetObject(OpenMode.ForRead).GetType().Equals(typeof(BlockReference)))
                            {
                                BlockReference br = tr.GetObject(ent_id, OpenMode.ForRead) as BlockReference;

                                Misc.WriteToTxtFile(string.Format("--BlockName:{0} BlockId:{1}\r\n", br.Name,br.BlockId));
                                BlockTableRecord btr_tmp = (tr.GetObject(br.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord);
                                Misc.WriteToTxtFile(string.Format("--BlockTableRecordName:{0} BTR_Id:{1}\r\n", btr_tmp.Name,btr_tmp.ObjectId));
                                DynamicBlockReferencePropertyCollection dbrp_col = br.DynamicBlockReferencePropertyCollection;
                                Misc.WriteToTxtFile(string.Format("---DynamicBlockProperty Count:{0} \r\n", dbrp_col.Count));
                                foreach ( DynamicBlockReferenceProperty dbrp in dbrp_col)
                                {
                                    Misc.WriteToTxtFile(string.Format("---DynamicBlockPropertyName:{0} Value:{1}\r\n", dbrp.PropertyName,dbrp.Value ));
                                }
                                Misc.WriteToTxtFile(string.Format("---AttTag Count:{0} \r\n", br.AttributeCollection.Count));
                                foreach (ObjectId att_id in br.AttributeCollection)
                                {
                                    AttributeReference ar = tr.GetObject(att_id, OpenMode.ForRead) as AttributeReference;
                                    Misc.WriteToTxtFile(string.Format("---AttTag:{0}  AttText:{1}\r\n", ar.Tag, ar.TextString));

                                }
                            }
                            j++;
                        }
                    }
                    i++;
                }

                tr.Commit();
            }
        }

        [CommandMethod("ShowUserData")]
        public static void ShowUserData()
        {
            Document doc = Core.GetCurrentActiveDoc();
            if (null != doc)
            {
                foreach( string key in doc.UserData)
                {
                    Misc.WriteToTxtFile(string.Format("Key:{0} | Value:{1}\r\n",key, doc.UserData[key]));
                }
            }
        }

        [CommandMethod("ShowDocName")]
        public static void ShowDocName()
        {//可以得到当前文档的完整路径
            Document doc = Core.GetCurrentActiveDoc();
            if (null != doc)
            {
                Misc.WriteToTxtFile(string.Format("DocName:{0} \r\n", doc.Name));
                
            }
        }

        [CommandMethod("MsgBoxShow")]
        public static void MsgBoxShow()
        {//可以得到当前文档的完整路径
            System.Windows.Forms.MessageBox.Show("AutoCAD MessageBox Test.", "Test",System.Windows.Forms.MessageBoxButtons.YesNoCancel);
        }

        /// <summary>
        /// 系统配置初始化
        /// </summary>
        [CommandMethod("SysCfgConfig_Init")]
        public static void SysCfgConfig_Init()
        {//可以得到当前文档的完整路径
            SystemConfig sc = new SystemConfig();
            xmlCatgPaper cp = new xmlCatgPaper();
            cp.PaperSpec = "N/A";
            cp.MaxItemCount = 10;
            xmlCatgPage catPag = new xmlCatgPage();
            catPag.Offset_X1 = 1;
            catPag.Offset_Y1 = 1;
            catPag.Offset_X2 = 1;
            catPag.Offset_Y2 = 1;
            catPag.Offset_X3 = 1;
            catPag.Offset_Y3 = 1;
            catPag.Offset_X4 = 1;
            catPag.Offset_Y4 = 1;
            catPag.MaxItemCount = 1;
            catPag.Step_X = 1;
            catPag.Step_Y = 1;
            cp.CatgPages.Add(catPag);
            sc.CatgPapers.Add(cp);

            xmlDrawPaper drwPag = new xmlDrawPaper();
            drwPag.PaperSpec = "N/A";
            xmlCatgItem ctgItm = new xmlCatgItem();
            ctgItm.Offset_X = 1;
            ctgItm.Offset_Y = 1;
            ctgItm.Key = "N/A";
            drwPag.CatgItems.Add(ctgItm);
            sc.DrawPapers.Add(drwPag);

            SysMisc.Serialization.SerializeToXml<SystemConfig>(sc, "AppConfig.xml");
        }

        [CommandMethod("AddMenu")]
        public static void AddMenu()
        {
            ContextMenuExtension cme = new ContextMenuExtension();
            cme.Title = "工程管理";
            MenuItem mil = new MenuItem("管理");
            mil.Click += Mil_Click;
            cme.MenuItems.Add(mil);
            mil = new MenuItem("输出");
            mil.Click += Mil_Click;
            cme.MenuItems.Add(mil);
        }

        [CommandMethod("OpenDWG")]
        public static void OpenDWG()
        {
            Core.OpenDoc(@"E:\项目\CAD工程文件管理\光纤全覆盖模板-施工图-路径图.dwg");
        }

        [CommandMethod("ShowAppPath")]
        public static void ShowAppPath()
        {
            //Misc.Alert(System.Windows.Forms.Application.ExecutablePath);
            Document doc = Application.DocumentManager.MdiActiveDocument;
            //当前执行程序集完整路径
            string File = Assembly.GetExecutingAssembly().Location;
            //执行程序集所在目录
            FileInfo assinfo = new FileInfo(File);
            string path = assinfo.DirectoryName;

            Misc.Alert(
              "\n当前程序序集路径: " + path
            );
        }

        private static void Mil_Click(object sender, EventArgs e)
        {
            MenuItem mi = (MenuItem)sender;
            switch( mi.Text)
            {
                case "管理":
                    {
                        Misc.Alert("管理 Click");
                    }
                    break;
                case "输出":
                    {
                        Misc.Alert("输出 Click");
                    }
                    break;
            }
        }

        [CommandMethod("spm")]
        public static void ShowDialog()
        {
            using(FormMain frmMain = new FormMain())
            {
                frmMain.ShowInTaskbar = false;
                Application.ShowModalDialog(frmMain);

            }
        }

        [CommandMethod("spm_init")]
        public static void SPM_Init()
        {
            string dic_path = Common.GetCurrentActiveDocPath();
            if (true == dic_path.Equals(""))
            {
                Misc.Alert("请至少打开一个DWG文件，否则无法完成初始化！");
                return;
            }

            Project prj = new Project(dic_path+@"\SppdProjectManage.spm");
            List<FileInfo> lst_fi = new List<FileInfo>();
            SysMisc.LogHelper.LogUpdateEvent += LogHelper_LogUpdateEvent;
            DirectoryInfo di = new DirectoryInfo(dic_path);
            string[] typs = { ".dwg", ".doc", ".xls", ".docx", ".xlsx"};
            FileInfo[] fis = di.GetFiles();
            foreach( FileInfo fi in fis)
            {
                foreach( string typ in typs)
                {
                    if(fi.Extension.Equals(typ))
                    {
                        lst_fi.Add(fi);
                        break;
                    }
                }
            }
            //写入工程文件列表
            foreach( FileInfo fi in lst_fi)
            {
                xmlFile xmlFile = new xmlFile();
                xmlFile.FileName = fi.Name;
                xmlFile.FileType = fi.Extension;

                prj.ProjectConfig.Files.Add(xmlFile);
            }
            //写入图纸名称列表
            prj.OpenAllFilesOfPrj();
            prj.GetAllPaperNames();
            string prjFullName = string.Format(@"{0}\{1}", Common.GetCurrentActiveDocPath(), "SppdProjectManage.spm");
            SysMisc.Serialization.SerializeToXml<ProjectConfig>(prj.ProjectConfig, prjFullName);
        }

        private static void LogHelper_LogUpdateEvent(SysMisc.LogHelper.LogType typ, Type t, string log)
        {
            Misc.WriteToTxtFile(log + "\r\n");
        }

        #region 实现IExtensionApplication接口
        public void Initialize()
        {
            //程序加载后，立即执行的代码
            Test();
        }

        public void Terminate()
        {
        }
        #endregion
    }
}
